package com.xinggq.pay.service.adaptor;

import com.xinggq.pay.service.context.AppIdContext;
import com.xinggq.pay.service.dto.ChannelInteractionRecordDTO;
import com.xinggq.pay.service.enums.PayChannelEnum;
import com.xinggq.pay.service.pay.channel.yse.utils.YseUtil;
import com.xinggq.pay.service.service.ChannelInteractionRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 银盛接口调用适配器
 * 1、完成接口调用
 * 2、保存接口调用记录
 * @Description
 * @Author xinggq
 * @Date 2025/9/12
 */

@Component
@Slf4j
@RequiredArgsConstructor
public class YseApiAdaptor {

  private final ChannelInteractionRecordService channelInteractionService;

  /**
   * 接口调用，
   * @param channelTradeNo
   * @param requestData
   * @param url
   * @return
   */
  public String post(String channelTradeNo, String requestData, String url) {
    log.info("银盛入参：{}", requestData);
    String responseData = YseUtil.httpPostSpecial(url, requestData);
    log.info("银盛出参：{}", responseData);
    return responseData;
  }


  /**
   * 支付接口调用
   * @param tradeNo
   * @param channelTradeNo
   * @param requestData
   * @param url
   * @return
   */
  public String pay(String tradeNo,String channelTradeNo, String requestData, String url) {
    String responseData = post(channelTradeNo, requestData, url);
    // 保存支付请求记录
    saveInteractionRecord(tradeNo,channelTradeNo, requestData, responseData);
    return responseData;
  }

  /**
   * 保存交互记录
   */
  private void saveInteractionRecord(String tradeNo,String channelTradeNo, String requestData,
      String responseData) {
    ChannelInteractionRecordDTO requestRecordDto = ChannelInteractionRecordDTO.builder()
        .tradeNo(tradeNo)
        .channelTradeNo(channelTradeNo)
        .payChannel(PayChannelEnum.YSE.getCode())
        .request(requestData)
        .response(responseData)
        .appId(AppIdContext.getAppId())
        .build();
    channelInteractionService.saveRequestRecord(requestRecordDto);
  }

}
